package com.sdjzu.wangfuying.disableautobrightness.ui;

import android.Manifest;
import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.mobstat.StatService;
import com.sdjzu.wangfuying.disableautobrightness.R;
import com.sdjzu.wangfuying.disableautobrightness.base.BaseActivity;
import com.sdjzu.wangfuying.disableautobrightness.service.ActivityMonitorServiceV10;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.OnClick;

public class GuideActivity extends BaseActivity {

    public static final String[] REQUIRED_PERMISSIONS = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };
    private static final String TAG = "GuideActivity";
    @BindView(R.id.activity_guide_btn_accessibility_service_status)
    Button mButtonAccessibility;
    @BindView(R.id.activity_guide_accessibility_service_status_container)
    View mContainerAccessibility;
    @BindView(R.id.activity_guide_btn_write_setting_permission_status)
    Button mButtonWriteSetting;
    @BindView(R.id.activity_guide_write_setting_permission_status_container)
    View mContainerWriteSetting;

    private static boolean isAccessibilityEnabled(Context mContext, Class<? extends AccessibilityService> serviceClass) {
        int accessibilityEnabled = 0;
        // TestService为对应的服务
        final String service = mContext.getPackageName() + "/" + serviceClass.getCanonicalName();
        try {
            accessibilityEnabled = Settings.Secure.getInt(mContext.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            Log.e(TAG, "Error finding setting, default accessibility to not found: " + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            String settingValue = Settings.Secure.getString(mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();

                    if (accessibilityService.equalsIgnoreCase(service)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide);
        requestPermission(REQUIRED_PERMISSIONS);
        // render setting fragment
        getFragmentManager()
                .beginTransaction()
                .replace(R.id.activity_guide_setting_container, new SettingFragment())
                .commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // check accessibility service
        if (checkAccessibility() & checkWriteSettingPermission()) {
            if (!getIntent().hasExtra("standby")) {
                if (isAccessibilityEnabled(getContext(), ActivityMonitorServiceV10.class)) {
                    Intent intent = new Intent(getContext(), ConfiguredPackagesActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        }
    }

    private boolean checkWriteSettingPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(this)) {
                mButtonWriteSetting.setText(R.string.activity_guide_write_setting_permission_disabled);
                mButtonWriteSetting.setBackgroundColor(getResources().getColor(R.color.colorDisabled));
                return false;
            }
        }
        mButtonWriteSetting.setText(R.string.activity_guide_write_setting_permission_enabled);
        mButtonWriteSetting.setBackgroundColor(getResources().getColor(R.color.colorEnabled));
        return true;
    }

    private boolean checkAccessibility() {
        if (isAccessibilityEnabled(getContext(), ActivityMonitorServiceV10.class)) {
            mButtonAccessibility.setText(R.string.activity_guide_accessibility_enabled);
            mButtonAccessibility.setBackgroundColor(getResources().getColor(R.color.colorEnabled));
            return true;
        } else {
            mButtonAccessibility.setText(R.string.activity_guide_accessibility_disabled);
            mButtonAccessibility.setBackgroundColor(getResources().getColor(R.color.colorDisabled));
            return false;
        }
    }

    @OnClick(R.id.activity_guide_btn_accessibility_service_status)
    void gotoSettingForOpeningAccessibilityService(Button button) {
        //if (!isAccessibilityEnabled(getContext(), ActivityMonitorServiceV10.class)) {
        gotoAccessibilitySetting();
        Toast.makeText(getContext(), R.string.activity_guide_toast_opening_accessibility_service_tooltip, Toast.LENGTH_SHORT).show();
        //}
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnClick(R.id.activity_guide_btn_write_setting_permission_status)
    void gotoWriteSettingPermissionGrantUI() {
        Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, 0x1);
    }

    private void gotoAccessibilitySetting() {
        final String ACTION = "action";
        final String ACTION_START_ACCESSIBILITY_SETTING = "action_start_accessibility_setting";
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.putExtra(ACTION, ACTION_START_ACCESSIBILITY_SETTING);
        // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, 0x0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*if (0x0 == requestCode) {
            checkAccessibility();
        } else if (0x1 == requestCode) {
            // checkWriteSettingPermission();
        }*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public static class SettingFragment extends PreferenceFragment {
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_settings);
            // add listener
            findPreference("pref_setting_key_theme").setOnPreferenceChangeListener((preference, newValue) -> {
                try {
                    if ("default".equals(newValue)) {
                        ((BaseActivity) getActivity()).setStyle(R.style.AppTheme_Default);
                    } else if ("blue".equals(newValue)) {
                        ((BaseActivity) getActivity()).setStyle(R.style.AppTheme_Blue);
                    } else {
                        Log.d(TAG, "不支持的主题色！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            });
            findPreference("pref_setting_key_disable_mtj").setOnPreferenceChangeListener((preference, newValue) -> {
                setupStatService((Boolean) newValue);
                return true;
            });
        }

        private void setupStatService(boolean disable) {
            if (disable) {
                StatService.autoTrace(getActivity().getApplicationContext(), false, false);
                Log.d(TAG, "已禁用移动统计");
            } else {
                StatService.autoTrace(getActivity().getApplicationContext());
                Log.d(TAG, "已启用移动统计");
            }
        }
    }
}
